package com.disys.mb;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.naming.ldap.LdapContext;
import javax.servlet.http.HttpServletRequest;

import com.disys.admin.security.LDAPAuth;
import com.disys.facade.LdapUsersFacade;
import com.disys.facade.UserFacade;
import com.disys.model.LdapUsers;
import com.disys.model.User;

@RequestScoped
@ManagedBean
public class LoginMB extends AbstractMB {
	@ManagedProperty(value = UserMB.INJECTION_NAME)
	private UserMB userMB;
	
	@ManagedProperty(value = LdapUsersMB.INJECTION_NAME)
	private LdapUsersMB ldapUsersMB;

	public void setLdapUsersMB(LdapUsersMB ldapUsersMB) {
		this.ldapUsersMB = ldapUsersMB;
	}

	private String email;
	private String password;

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String login() {
		UserFacade userFacade = new UserFacade();
		LdapUsersFacade ldapUsersFacade = new LdapUsersFacade();
		
		//validate user from LDAP first
		LDAPAuth obj = new LDAPAuth();
		LdapContext ldapContext = obj.getLdapContext(email,password);
		if(ldapContext != null){
			obj.closeConnection(ldapContext);
		}else{
			displayErrorMessageToUser("Invalid LDAP Credentials");
			return null;
		}
		
		String baseDn = (String) FacesContext.getCurrentInstance().getExternalContext().getRequestMap().get("baseDn");
		//check if the user is in our local db or not.
		LdapUsers us = ldapUsersFacade.isAuthorized(baseDn);
		if(us == null){
			displayErrorMessageToUser("User not found in the database.");
			return null;
		}else{
			ldapUsersMB.setUser(us);
			FacesContext context = FacesContext.getCurrentInstance();
			HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
			request.getSession().setAttribute("user", us);
			return "/pages/protected/users/allusers.xhtml";
		}
	}

	public void setUserMB(UserMB userMB) {
		this.userMB = userMB;
	}	
}